//
//  HomeViewController.m
//  HxgProject
//
//  Created by hxg on 2018/3/1.
//  Copyright © 2018年 XMYY-19. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeService.h"
#import "UIColor+HEX.h"
#import "UIButton+Extention.h"
#import "ResObject.h"

#import "PackageInfo.h"
#import <IQKeyboardReturnKeyHandler.h>
#import "JK_BasicPackageInfo.h"


#define btnH 89.0f
#define btnW 125.0f

// 0代表不显示服务费 1代表显示服务费
#define isShowServiceMoney 1

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    IQKeyboardReturnKeyHandler *returnKeyHandler;
}

@property (nonatomic, strong) UITableView *borrowTableView;
@property (nonatomic, retain) NSIndexPath * selectedIndexPath;

// 借款1000的按钮
@property (nonatomic, strong)  UIButton *num1Btn;
// 借款2000的按钮
@property (nonatomic, strong)  UIButton *num2Btn;
// 全局提交按钮
@property (nonatomic, strong) UIButton *submitBtn;


// 按钮是否可以被点击
@property (nonatomic, assign) BOOL isClick;
// 套餐内容(表格的数据源)
@property (nonatomic, strong) NSMutableArray *packageDataSourceArr;


// 选中的套餐对象
@property (nonatomic, strong) JK_BasicPackageInfo *selectedPackInfo;
// 1500的套餐对象
@property (nonatomic, strong) JK_BasicPackageInfo *lessPackInfo;
// 2000的套餐对象
@property (nonatomic, strong) JK_BasicPackageInfo *morePackInfo;


@end

@implementation HomeViewController


#pragma mark - ######cycle Life<##>######
- (void)viewDidLoad {
    [super viewDidLoad];

    returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
    
    [self getPakageDetail];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return 2;
    }
    return 15.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (0 == section)
    {
        return [[UIView alloc] init];
    }
    return [[UIView alloc] init];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];
    }

    if (0 == indexPath.section)
    {
        if ([self.selectedIndexPath isEqual:indexPath]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        cell.textLabel.text = [NSString stringWithFormat:@"%@",self.selectedPackInfo.borrowDays];
        cell.textLabel.font = mainFont;
        cell.textLabel.textColor = defaultFontColor;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section)
    {
        if (self.selectedIndexPath)
        {
            UITableViewCell * cell = [tableView cellForRowAtIndexPath:self.selectedIndexPath];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        
        self.selectedIndexPath = indexPath;
    }
    
    [self.borrowTableView reloadData];
}

#pragma mark - ######custom Event<##>######
- (void)getPakageDetail
{
    __weak HomeViewController *weakSelf = self;
    HomeService *homeService = [[HomeService alloc] init];
    [homeService getBaseBorrowPakageWithCallBack:^(ResObject *resObj, NSMutableArray *arr) {
        
        if (arr
            && arr.count != 0) {
            weakSelf.packageDataSourceArr = arr;
            
            // 对数据源赋值
            weakSelf.lessPackInfo = arr[1];
            weakSelf.morePackInfo = arr[0];
            weakSelf.selectedPackInfo = arr[1];
            
            NSLog(@"currentThread==>%@",[NSThread currentThread]);
        }
        
        NSLog(@"currentThread=11=>%@",[NSThread currentThread]);

        // 加载两个金额按钮
        [weakSelf setUpMoneyBtns];
        
        // 加载提交按钮
        [self loadSubmitBtn];
    }];
}


- (void)setUpMoneyBtns{
    self.navigationItem.title = @"套餐";
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:mainFont,
       NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"]}];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:68.0f/255.0f green:161.0f/255.0f blue:247.0f/255.0f alpha:1.0f];
    self.navigationController.navigationBar.barTintColor = kNavagationBarBgColor;
    
    self.num1Btn =  [[UIButton alloc] init];
    self.num1Btn.tag = 0;
    [self.num1Btn setTitle:[NSString stringWithFormat:@"%@",self.lessPackInfo.moneyNum]
                     color:kCommonBtnBgColor
                      font:mainFont];
    
    self.num2Btn =  [[UIButton alloc] init];
    self.num2Btn.tag = 1;
    [self.num2Btn setTitle:[NSString stringWithFormat:@"%@",self.morePackInfo.moneyNum]
                     color:[UIColor colorWithHexString:@"97CEFA"]
                      font:mainFont];
    [self.view addSubview:self.num1Btn];
    [self.view addSubview:self.num2Btn];
    [self.num1Btn addTarget:self
                     action:@selector(midBtn:)
           forControlEvents:UIControlEventTouchUpInside];
    [self.num2Btn addTarget:self
                     action:@selector(midBtn:)
           forControlEvents:UIControlEventTouchUpInside];
    
    [self.num1Btn makeConstraints:^(MASConstraintMaker *make) {
        
        if (@available(iOS 11.0,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(KIphoneSize_Height(20.0f));
        }else{
            make.top.equalTo(self.view.mas_top).offset(84);
        }
        make.centerX.equalTo(self.view.mas_centerX).offset(-self.view.frame.size.width/4.0f);
        make.size.mas_equalTo(CGSizeMake(btnW, btnH));
    }];
    
    [self.num2Btn makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.num1Btn.mas_top);
        make.centerX.equalTo(self.view.mas_centerX).offset(self.view.frame.size.width/4.0f);
        make.size.mas_equalTo(CGSizeMake(btnW, btnH));
    }];
    
    [self.view addSubview:self.borrowTableView];
    [self.borrowTableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.num1Btn.mas_bottom).offset(20.0f);
        make.left.equalTo(self.view.mas_left);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 80.0f));
    }];
}

- (void)loadSubmitBtn {
    
    self.submitBtn = [[UIButton alloc] init];
    [self.view addSubview:self.submitBtn];
    [self.submitBtn setTitle:@"提交"
                       color:kCommonBtnBgColor
                        font:mainFont];
    self.submitBtn.showsTouchWhenHighlighted = YES;
    
    [self.submitBtn addTarget:self
                       action:@selector(submitData:)
             forControlEvents:UIControlEventTouchUpInside];
    
    //在非tabBarController中使用
    UITabBarController *tabBarVC = [[UITabBarController alloc] init];
    CGFloat tabBarHeight = tabBarVC.tabBar.frame.size.height;
    [self.submitBtn makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.view.mas_bottom).offset(-tabBarHeight - self.view.frame.size.height / 9.0f);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width * 3 / 4.0f, 60.0f));
    }];
}


- (void)midBtn:(UIButton *)btn
{
    NSLog(@"btn.isSelected===%@",btn.isSelected ? @"YES":@"NO" );
    
    // 先判断是哪个按钮
    if (1 == btn.tag) {
        // 如果是第二个按钮,再判断选中状态
        [btn setBackgroundColor:kCommonBtnBgColor];
        [self.num1Btn setBackgroundColor:[UIColor colorWithHexString:@"97CEFA"]];
        [self setSubmitBtnDisable];
    } else {
        [btn setBackgroundColor:kCommonBtnBgColor];
        [self.num2Btn setBackgroundColor:[UIColor colorWithHexString:@"97CEFA"]];
        [self setSubmitBtnEnable];
    }
    
    self.selectedPackInfo = self.packageDataSourceArr[(self.packageDataSourceArr.count -1 - btn.tag)];
    
    self.selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    [self.borrowTableView reloadData];
}

- (void)submitData:(UIButton *)sender
{
    [SVProgressHUD showWithStatus:@"加载中..."];
    
    if (!self.isClick) {
        [SVProgressHUD showErrorWithStatus:@"请先认证所有信息,再提交申请!"];
        [SVProgressHUD dismissWithDelay:1.0f];

        return;
    }
    
    [self setSubmitBtnDisable];
    
    [self btnClickedOperations:sender];
    
    HomeService *homeService = [[HomeService alloc] init];
    [homeService saveBaseBorrowPackage:self.selectedPackInfo withCallBack:^(ResObject *resObje) {
        if (resObje.isSuccess)
        {
            [SVProgressHUD showSuccessWithStatus:@"提交成功!"];
        } else {
            [SVProgressHUD showErrorWithStatus:resObje.errMsg];
        }
        [SVProgressHUD dismissWithDelay:1.0f];
    }];
}

- (void)btnClickedOperations:(UIButton *)btn {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"btnClickedOperations");
        [self setSubmitBtnEnable];
    });
}

#pragma mark - ###### 按钮交互的开闭 ######

// 关闭提交按钮交互
- (void)setSubmitBtnDisable {
    self.submitBtn.userInteractionEnabled = NO;//交互关闭
    self.submitBtn.alpha = 0.4;//透明度
}

// 打开提交按钮交互
- (void)setSubmitBtnEnable {
    self.submitBtn.userInteractionEnabled = YES;//交互打开
    self.submitBtn.alpha = 1;//透明度
}

#pragma mark - ######getter、setter######
- (NSIndexPath *)selectedIndexPath
{
    if (!_selectedIndexPath)
    {
        _selectedIndexPath =  [NSIndexPath indexPathForRow:0 inSection:0];
    }
    return _selectedIndexPath;
}

- (UITableView *)borrowTableView
{
    if (!_borrowTableView)
    {
        _borrowTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _borrowTableView.delegate = self;
        _borrowTableView.dataSource = self;
        _borrowTableView.scrollEnabled = NO;
        _borrowTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, KIphoneSize_Height(20.0f))];
    }
    
    return _borrowTableView;
}

- (BOOL)isClick
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kContactAuthenRes]
        && [[NSUserDefaults standardUserDefaults] boolForKey:kPersonInfoAuthenRes]
        && [[NSUserDefaults standardUserDefaults] boolForKey:kXinYuAuthenRes]
        && [[NSUserDefaults standardUserDefaults] boolForKey:kCompanyAuthenRes]
        && [[NSUserDefaults standardUserDefaults] boolForKey:kBankInfoAuthenRes]
        ) {
        return YES;
    } else {
        return NO;
    }
}

@end
